<template>
    <div>
        <!-- 搜索bar -->
        <div id="selectBar">
            <el-input placeholder="请输入愿望关键字" v-model="selectBarData.name" clearable style="width: 180px;"></el-input>
            <el-select v-model="selectBarData.type" placeholder="请选择愿望类型">
                <el-option v-for="(item, index) in wishTypeData" :key="index" :label="item" :value="item"></el-option>
            </el-select>
            <div id="completedBar">
                <span id="completedText">完成</span>
                <el-switch v-model="selectBarData.completed" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
            </div>
            <el-date-picker v-model="selectBarData.time" type="date" placeholder="请选择时间"></el-date-picker>
            <el-button icon="el-icon-search" class="search" circle @click="search(true)"></el-button>
        </div>
        <!-- 愿望列表 -->
        <ul id="wishBar">
            <li v-for="(item, index) in wishData" :key="item.id" @click="wishBarShow(item, index)">
                <div class="wishItem" ref="wishItem">
                    <div class="wishIntroduction">
                        <p class="wishName">{{ item.name }}</p>
                        <i class="el-icon-check finishIcon" v-if="item.completed"></i>
                    </div>
                    <div class="dropDownBar" ref="dropDownBar">
                        <div class="barLine"></div>
                        <div class="imgBox" @click.stop>
                            <el-image :src="GLOBAL.OSSImageUrlRoot + 'WishImage/' + item.id + '.png'" fit="contain"
                                :preview-src-list="[GLOBAL.OSSImageUrlRoot + 'WishImage/' + item.id + '.png']" lazy>
                                <div slot="error" class="image-slot">
                                    <i class="el-icon-picture-outline"></i>
                                </div>
                            </el-image>
                        </div>
                        <p class="descriptionText"
                            v-if="item.description != null && item.description != 'null' && item.description != '' && item.description != ' '">
                            描述：{{ item.description }}</p>
                        <p class="type">类型：{{ item.type }}</p>
                        <p class="time" :class="item.finishTime == null ? 'finishTime' : ''">许愿时间：{{ item.time
                        }}</p>
                        <p class="finishTime" v-if="item.finishTime != null">完成时间：{{ item.finishTime }}</p>
                        <div class="operate" v-show="item.listButtonShow">
                            <el-button @click.stop="showStatus.WishEditShow = true; currentWish = item" type="primary"
                                icon="el-icon-edit" circle></el-button>
                            <el-button v-if="!item.completed" type="success" icon="el-icon-check"
                                @click.stop="wishCompletedChange(item, true)" circle></el-button>
                            <el-button v-if="item.completed" type="info" icon="el-icon-close"
                                @click.stop="wishCompletedChange(item, false)" circle></el-button>
                            <el-button @click.stop="showStatus.deleteWish = true; currentWish = item" type="danger"
                                icon="el-icon-delete" circle></el-button>
                        </div>
                    </div>
                </div>
            </li>
        </ul>
        <!-- 分页按钮 -->
        <div id="paging">
            <el-pagination layout="prev, pager, next" :page-size="pageSize" :total="total"
                @current-change="pageCurrentChange">
            </el-pagination>
        </div>
        <!-- 编辑提示框 -->
        <el-dialog title="编辑心愿" :visible.sync="showStatus.WishEditShow">
            <el-form :model="currentWish" label-position="top">
                <el-form-item>
                    <span>id：{{ currentWish.id }}</span>
                </el-form-item>
                <el-form-item label="封面图片上传">
                    <el-image :src="GLOBAL.OSSImageUrlRoot + 'WishImage/' + currentWish.id + '.png'" fit="contain"
                        style="height: 80px;"
                        :preview-src-list="[GLOBAL.OSSImageUrlRoot + 'WishImage/' + currentWish.id + '.png']">
                        <div slot="error" class="image-slot">
                            <i class="el-icon-picture-outline"></i>
                        </div>
                    </el-image>
                    <el-upload class="upload-demo" :action="uploadUrl" :before-upload="beforeImgUpload" auto-upload
                        :headers="imgUploadHeaders" :on-error="imgUploadError" :on-success="imgUploadSuccess" :limit="1"
                        :on-exceed="handleExceed" accept=".jpg, .png" list-type="picture" :multiple="false"
                        :file-list="fileList" name="file">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <el-button size="small" type="danger" @click.stop="deleteWishImage">删除图片</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，无需点击提交自动上传</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="心愿名称">
                    <el-input v-model="currentWish.name" type="input" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    心愿类型
                    <div>
                        <div class="typeBar">
                            <p>1.选择已有的愿望类型</p>
                            <el-select v-model="currentWish.type">
                                <el-option v-for="(item, index) in wishTypeData" :key="index" :value="item"
                                    :label="item"></el-option>
                            </el-select>
                            <p>2.创建新的愿望类型</p>
                            <el-input v-model="currentWish.type" type="input" clearable></el-input>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="心愿描述">
                    <el-input v-model="currentWish.description" type="textarea" autosize></el-input>
                </el-form-item>
                <el-form-item>
                    <span id="completedText">完成</span>
                    <el-switch @change="completedChange" v-model="currentWish.completed" active-color="#13ce66"
                        inactive-color="#ff4949"></el-switch>
                </el-form-item>
                <el-form-item label="许愿时间">
                    <el-date-picker type="date" placeholder="选择日期" v-model="currentWish.time"
                        value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
                <el-form-item label="完成时间">
                    <el-date-picker @change="finishDateChange" type="date" placeholder="选择日期"
                        v-model="currentWish.finishTime" value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="showStatus.WishEditShow = false">取 消</el-button>
                <el-button type="primary" @click="editWishUpdate(); showStatus.WishEditShow = false">提 交</el-button>
            </div>
        </el-dialog>
        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="showStatus.deleteWish" width="30%">
            <span>确定删除该愿望么</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showStatus.deleteWish = false;">取 消</el-button>
                <el-button type="primary" @click="deleteWish(); showStatus.deleteWish = false;">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            selectBarData: {
                name: null, // 愿望名
                time: null, // 许愿时间
                completed: false, // 是否完成
                type: null, // 愿望类型
            }, // 搜索bar数据
            wishData: [], // 愿望数据列表
            wishTypeData: [], // 愿望类型数据列表
            currentPage: 1, // 当前页
            pageSize: 10, // 页大小
            total: 0, // 数据总数
            searchOrNot: false, // 是否搜索状态量，用于确定翻页后数据从那个方法得到
            currentWish: {}, // 当前选中愿望
            showStatus: {
                WishEditShow: false, // 控制愿望编辑框的显示/隐藏
                deleteWish: false, // 控制删除愿望提示框的显示/隐藏
            }, // 显示/隐藏状态量
            fileList: [], // 文件(图片)上传的文件list
            imgUploadHeaders: { 'Token': sessionStorage.getItem('token') }, // 请求头token信息，用于图片上传后端认证
        }
    },
    methods: {
        // 当element ui 的页数改变，同步页数
        pageCurrentChange(val) {
            this.currentPage = val // 更改当前页
            if (this.searchOrNot) { // 若搜索过，就用筛选搜索的方式查询数据
                this.search(false)
                return
            }
            this.getWishData() // 默认，请求所有数据
        },
        // 获取愿望数据
        getWishData() {
            this.$axios({
                method: 'post',
                url: '/wish/login/getAllWish/' + this.currentPage + '/' + this.pageSize,
            }).then(res => {
                res.data.data.data.forEach(element => {
                    element.listButtonShow = false
                    element.time = element.time.slice(0, 10)
                    if (element.finishTime != null) element.finishTime = element.finishTime.slice(0, 10)
                    element.completed = element.completed ? true : false
                });
                this.wishData = res.data.data.data
                this.total = res.data.data.total
            })
        },
        // 筛选搜索获得数据,参数意思：表示是翻页查找(不需要重设页状态)，还是按钮点击查找(需要重设页状态)
        search(buttonSearchOrNot) {
            if (buttonSearchOrNot) { // 若为按钮点击搜索,重设页状态
                this.currentPage = 1
                this.total = 0
            }
            this.searchOrNot = true // 改变搜索状态量
            let data = new FormData()
            if (this.selectBarData.name != null) data.append("name", this.selectBarData.name)
            if (this.selectBarData.time != null) data.append("time", this.selectBarData.time)
            if (this.selectBarData.type != null) data.append("type", this.selectBarData.type)
            data.append("completed", this.selectBarData.completed ? 1 : 0)
            this.$axios({
                method: 'post',
                url: '/wish/login/searchWish/' + this.currentPage + '/' + this.pageSize,
                data: data,
                headers: {
                    'Content-Type': 'application/x-www-form-urlcoded'
                }
            }).then(res => {
                res.data.data.data.forEach(element => {
                    element.time = element.time.slice(0, 10)
                    element.listButtonShow = false
                    if (element.finishTime != null) element.finishTime = element.finishTime.slice(0, 10)
                    element.completed = element.completed ? true : false
                });
                this.total = res.data.data.total
                this.wishData = res.data.data.data
            })
        },
        // 获取所有愿望类型
        getAllWishType() {
            this.$axios({
                method: 'post',
                url: '/wish/login/getAllType'
            }).then(res => {
                this.wishTypeData = res.data
            })
        },
        // 显示愿望详情
        wishBarShow(item, index) {
            const liCol = this.$refs.dropDownBar[index]
            let height = liCol.offsetHeight
            if (height == 0) {
                height = liCol.scrollHeight
                liCol.style.height = height + 'px'
                item.listButtonShow = true
            } else {
                liCol.style.height = '0px'
                item.listButtonShow = false
            }
        },
        // 处理图片上传多了的提示事件
        handleExceed() {
            this.$message({
                type: 'error',
                message: '限制只能上传一个文件哦',
                showClose: true,
            })
        },
        // 图片文件上传出现错误的提示事件
        imgUploadError() {
            this.$message({
                message: '文件上传出现错误X.X',
                type: 'error',
                showClose: true,
            })
        },
        // 图片文件上传成功的提示事件
        imgUploadSuccess() {
            this.$message({
                message: '上传成功',
                type: 'success',
                showClose: true
            })
        },
        // 图片文件上传前的文件类型检查
        beforeImgUpload(file) {
            if (this.getfileName(file.name) != '.jpg' && this.getfileName(file.name) != '.png') {
                this.$message({
                    message: '上传封面图片文件格式只能为jpg或png',
                    type: 'error',
                    showClose: true,
                })
                return false
            }
        },
        // 获取文件后缀工具函数
        getfileName(filename) {
            // 转换为小写
            const pos = filename.toLowerCase().lastIndexOf('.')
            let suffix = ''
            if (pos !== -1) {
                suffix = filename.substring(pos)
            }
            return suffix
        },
        // 更新愿望提交
        editWishUpdate() {
            // 检查数据完整性
            if (this.currentWish.name == null || this.currentWish.name == '' || this.currentWish.type == null ||
                this.currentWish.type == '' || this.currentWish.time == null || this.currentWish.time == '') {
                this.$message({
                    type: 'error',
                    message: '请完善愿望内容后再提交哦',
                    showClose: true,
                })
                return
            }
            let data = new FormData()
            data.append("id", this.currentWish.id)
            data.append("name", this.currentWish.name)
            data.append("time", new Date(this.currentWish.time))
            data.append("type", this.currentWish.type)
            data.append("description", this.currentWish.description)
            data.append("completed", this.currentWish.completed ? 1 : 0)
            if (this.currentWish.finishTime != null) data.append("finishTime", new Date(this.currentWish.finishTime))
            // 发送请求
            this.$axios({
                method: 'post',
                url: 'wish/login/updateWish',
                data: data,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).then(res => {
                if (res.data) {
                    this.$message({
                        type: 'success',
                        message: '提交成功',
                        showClose: true,
                    })
                    this.$router.go(0)
                } else {
                    this.$message({
                        type: 'error',
                        message: '操作出现错误了X.X',
                        showClose: true,
                    })
                }
            })
        },
        // 当完成时间改变触发事件
        finishDateChange(value) {
            if (value != null && value != '') { // 若有值，修改完成状态量为true
                this.currentWish.completed = true
            } else {
                this.currentWish.completed = false
            }
        },
        // 当完成按钮改变触发事件
        completedChange(value) {
            if (value) { // 若完成，修改完成时间为现在
                this.currentWish.finishTime = new Date()
            } else {
                this.currentWish.finishTime = null
            }
        },
        // 删除愿望
        deleteWish() {
            this.$axios({
                method: 'post',
                url: 'wish/login/deleteWish/' + this.currentWish.id
            }).then(res => {
                if (res.data) {
                    this.$message({
                        type: 'success',
                        message: '还有更多心愿等待完成哦~',
                        showClose: true,
                    })
                    this.$router.go(0)
                } else {
                    this.$message({
                        type: 'error',
                        message: '删除失败，操作出现错误了X.X',
                        showClose: true,
                    })
                }
            })
        },
        // 愿望是否完成更新事件
        wishCompletedChange(item, completed) {
            let successMsg = completed ? '心愿实现啦*^O^*' : '心愿还在来的路上哦(≧▽≦)'
            this.$axios({
                method: 'post',
                url: 'wish/login/wishCompletedChange/' + item.id + '/' + (completed ? 1 : 0)
            }).then(res => {
                if (res.data) {
                    this.$message({
                        type: 'success',
                        message: successMsg,
                        showClose: true,
                    })
                    item.completed = completed
                    // 若为完成 获取当天年月日 给finishTime
                    if (item.completed) {
                        let now = new Date()
                        let month = now.getMonth() + 1
                        let day = now.getDate()
                        if (month >= 1 && month <= 9) {
                            month = "0" + month;
                        }
                        if (day >= 0 && day <= 9) {
                            day = "0" + day;
                        }
                        item.finishTime = now.getFullYear() + '-' + month + '-' + day
                    } else {
                        item.finishTime = null
                    }
                } else {
                    this.$message({
                        type: 'error',
                        message: '操作出现错误了X.X',
                        showClose: true,
                    })
                }
            })
        },
        // 删除愿望图片
        deleteWishImage() {
            this.$axios({
                method: 'post',
                url: '/wish/login/deleteWishImage/' + this.currentWish.id
            }).then(res => {
                if (res.data) {
                    this.$message({
                        showClose: true,
                        message: '删除成功',
                        type: 'success'
                    })
                } else {
                    this.$message({
                        showClose: true,
                        message: '删除失败，出现错误了X.X',
                        type: 'error'
                    })
                }
            })
        }
    },
    computed: {
        uploadUrl() { // 请求上传图片的url地址
            return this.$axios.defaults.baseURL + '/wish/login/uploadWishImage/' + this.currentWish.id
        },
    },
    mounted() {
        this.getWishData()
        this.getAllWishType()
    }
}
</script>

<style lang="scss" scoped>
#selectBar {
    margin: 20px auto;
    display: flex;
    justify-content: center;
}

#completedBar {
    margin: auto 20px;
}

#completedText {
    margin-right: 10px;
}

.search {
    background-color: #202020;
    color: #fff;
}

#wishBar {
    display: flex;
    flex-flow: column;
}

.wishItem {
    width: 80%;
    border-radius: 20px;
    margin: 20px auto 0 auto;
    background-color: $color-background-assistant;
    position: relative;
    cursor: pointer;
}

.wishIntroduction {
    position: relative;
}

.wishName {
    font-size: $font-size-medium;
    font-weight: $font-weight-medium;
    height: 100%;
    width: 80%;
    margin: 20px 0 20px 20px;
    display: inline-block;
    color: $color-main-text;
    user-select: none;
}

.finishIcon {
    font-size: $font-size-large;
    font-weight: $font-weight-medium;
    position: absolute;
    right: 5%;
    top: 50%;
    transform: translate(0, -50%);
    color: $color-main-text;
}

.dropDownBar {
    height: 0px;
    overflow: hidden;
    transition: all .5s;
}

.barLine {
    width: 90%;
    border-bottom: $color-text .5px solid;
    border-radius: 20px;
    margin: 0 auto 10px auto;
}

.imgBox {
    margin: 20px auto;
    max-width: 50%;
    min-width: 30%;
    min-height: 30%;
    text-align: center;
    overflow: hidden;
}

.imgBox i {
    background-color: rgba(0, 0, 0, .1);
    font-size: $font-size-large;
    padding: 30px;
    border-radius: 10px;
}

.descriptionText,
.type,
.time,
.finishTime {
    margin: 0 0 5px 40px;
    width: 70%;
}

.finishTime {
    margin-bottom: 20px;
}

.operate {
    opacity: .6;
    position: absolute;
    bottom: 20px;
    right: 20px;
}

#authorityText {
    margin-right: 10px;
}
</style>

<style scoped="scoped">
/* 搜索框 */
/deep/#selectBar .el-input__inner {
    background-color: #202020;
    color: #fff;
}

#selectBar .el-input {
    margin: auto 20px;
}

/* 分页 */

/deep/.el-pagination {
    display: flex;
    justify-content: center;
    margin: 20px auto;
    color: #202020;
}

/deep/.el-pagination button {
    color: #fff;
    background-color: #202020;
}

/deep/ .el-pager li.active {
    color: rgb(255, 150, 50);
}

/deep/ .number {
    color: #fff;
}

/deep/ .number:hover {
    color: rgb(255, 150, 50);
}

/deep/.el-pager li {
    background-color: #202020;
}
</style>

